<template>
    <el-dialog title="添加微信客服" :visible.sync="dialogTableVisible" :show-close="true" :center="true" top="10vh" :before-close="beforeClose" :close-on-click-modal="false">
        <div class="dialogVue">
            <div class="stepVue flex_center">
                <div class="flex_column align_center flex_1">
                    <div class="dot" :class="{active: current===1}">1</div>
                    <span :class="{textActive: current===1}">设置AI客服</span>
                </div>
                <div class="line"></div>
                <div class="flex_column align_center flex_1">
                    <div class="dot" :class="{active: current===2}">2</div>
                    <span :class="{textActive: current===2}">AI模型选择</span>
                </div>
                <div class="line"></div>
                <div class="flex_column align_center flex_1">
                    <div class="dot" :class="{active: current===3}">3</div>
                    <span :class="{textActive: current===3}">绑定微信号</span>
                </div>
            </div> 

            <div class="stepContent">
                <!-- 设置AI客服 -->
                <template v-if="current===1">
                    <div class="inpVue" style="margin-top: 40px">
                        <div class="label">AI客服描述</div>
                        <textarea placeholder="输入客服的介绍，可填写使用者姓名，联系电话等基本信息。" v-model="name" :maxlength="50"></textarea>
                    </div>
                    <div class="inpVue">
                        <div class="flex_between align_center">
                            <div class="label">私聊开场白(添加微信好友后，将自动给用户发送开场白)</div>
                            <el-switch v-model="openingStatus" inactive-color="#999" active-color="#0147fd"></el-switch>
                        </div>
                        <textarea v-model="openingRemarks" :maxlength="80"></textarea>
                    </div>
                    <div class="inpVue">
                        <div class="label" style="margin-bottom: 10px;">关联知识库</div>
                        <el-select v-model="datasetId" placeholder="请选择知识库" filterable  style="width: 100%;" @change="handleChange" clearable>
                            <el-option v-for="item in datasetList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </div>
                    <div class="inpVue" style="margin-top: 20px;">
                        <div class="flex_between align_center">
                            <div class="label">开启AI回复</div>
                            <el-switch v-model="aiStatus" inactive-color="#999" active-color="#0147fd"></el-switch>
                        </div>
                        <div style="font-size: 12px; color: #999; padding-top: 10px;">关闭后，AI将不会对客户回复消息</div>
                    </div> 
                    <div class="btnVue flex_center">
                        <div class="cancel" @click="beforeClose">取消</div>
                        <div style="width: 20px;"></div>
                        <div class="btn" @click="nextOneFun">下一步</div>
                    </div>
                </template>

                <!-- AI模型选择 -->
                <template v-if="current===2">
                    <div class="selectVue flex_wrap flex_between" style="margin-top: 40px">
                        <div class="select" v-for="(item, index) in promptList" :key="index" :class="{active: modelId===item.id}" @click="modelId=item.id">
                            <div class="flex" style="padding-bottom: 10px">
                                <span style="color: #101010; font-size: 12px; font-weight: 600;">{{ item.name }}</span>
                                <span style="color: #101010; font-size: 12px; font-weight: 600; padding: 0 10px">{{ item.sex }}</span>
                                <span style="color: #101010; font-size: 12px; font-weight: 600;">{{ item.age }}岁</span>
                            </div>
                            <div class="li">{{ item.answerMethod }}</div>
                            <div class="li">{{ item.style }}</div>
                            <div class="li">{{ item.language }}</div>
                        </div>
                    </div>    

                    <div class="btnVue flex_center">
                        <div class="cancel" @click="current=1">上一步</div>
                        <div style="width: 20px;"></div>
                        <div class="btn" @click="nextTwoFun">
                            <span class="el-icon-loading" v-if="loading"></span>
                            <span v-else style="color: #fff;">下一步</span>
                        </div>
                    </div>
                </template>

                <template v-if="current===3">
                    <div class="h8 text_center">使用微信扫码绑定AI客服</div>
                    <div class="code margin20 flex_center align_center">
                        <img :src="loginCode" style="width: 100%; height: 100%;" v-if="loginCode">
                        <span class="el-icon-loading" v-else></span>
                    </div>
                    <div class="h8 text_center" style="margin-top: -30px;">扫码成功后，会同步通讯录，请勿关闭弹窗</div>
                    <template v-if="show1">
                        <div class="flex_center align_center margin20">
                            <span class="el-icon-warning" style="color: #d81e06; font-size: 18px;"></span>
                            <span style="color: #AAA; padding-left: 5px;">扫码页面停留时间过长，{{count1}} 秒后将自动关闭窗口</span>
                        </div>
                        <div class="btn margin20" @click="cancelTimer1">取消关闭</div>
                    </template>
                    <!-- <template v-if="show2">
                        <div class="flex_center align_center margin20">
                            <span class="el-icon-warning" style="color: #d81e06; font-size: 18px;"></span>
                            <span style="color: #AAA; padding-left: 5px;">二维码 {{count2}} 秒后即将刷新</span>
                        </div>
                    </template> -->
                </template>
            </div>
        </div>
    </el-dialog>
</template>


<script>
import { toast } from '@/common/tools'
export default {
    props: {
        dialogTableVisible: {
            type: Boolean,
            default: false
        }
    },
    data(){
        return {
            promptList: [],
            datasetList: [],
            current: 1,
            name: "",
            openingStatus: false,
            openingRemarks: "我是【客服名称】，很高兴为您服务。无论您有任何问题或需要帮助，都可以直接发送消息。我会尽快为您提供解答和协助。",
            groupOpeningStatus: 0,
            groupOpeningRemarks: "",
            datasetId: "",
            aiStatus: true,
            modelId: "",
            loading: false,
            loginCode: "",
            id: "",

            // 若用户打开二维码弹窗 20 分钟后，将提示’扫码页面停留超时，10秒后将自动关闭窗口’点击‘取消关闭’，保留当前弹窗
            timer1: null,
            show1: false,
            count1: 1200,

            //前端每隔 5 分钟会向服务器获取二维码，获取前 10 秒内会倒计时提示：‘二维码 10 秒后即将刷新
            timer2: null,
            // show2: false,
            count2: 5,

            timer3: null,
        }
    },
    methods: {
        // 获取提示词列表
        getPromptWord(){
            this.$post("/front/prompt").then(res=>{
                this.promptList = res.data.obj
            })
        },

        // 获取知识库列表
        getRepositoryList(){
            this.$post("/front/dataset/datasetList", {
                pageNum: 1,
                pageSize: 1000
            }).then(res=>{
                this.datasetList = res.data.obj.list
            })
        },

        handleChange(e){
            this.datasetId = e
        },

        beforeClose(){
            if(this.timer1) this.cancelTimer1()
            if(this.timer2) this.cancelTimer2() 
            if(this.timer3) this.cancelTimer3()
            this.current = 1
            this.datasetId = ""
            this.name = ""
            this.aiStatus = true
            this.openingStatus = false
            this.modelId = ""
            this.count1 = 1200
            this.count2 = 5
            this.openingRemarks = "我是【客服名称】，很高兴为您服务。无论您有任何问题或需要帮助，都可以直接发送消息。我会尽快为您提供解答和协助。"
            this.$emit("beforeClose")
        },

        // 完成第一步
        nextOneFun(){
            if(!this.name) return toast(1, "请输入AI客服描述")
            if(this.openingStatus && !this.openingRemarks) return toast(1, "请输入私聊开场白")
            this.current = 2
        },

        // 完成第二步
        nextTwoFun(){
            if(!this.modelId)  return toast(1, "请选择AI角色模型")
            if(this.loading) return
            this.loading = true
            this.$post("/front/userWechat/createWechat", {
                name: this.name,
                promptId: this.modelId,  //AI模板选择
                openingRemarks: this.openingRemarks, //开场白
                groupOpeningStatus: this.groupOpeningStatus ? 1 : 0,
                groupOpeningRemarks: this.groupOpeningRemarks,
                aiStatus: this.aiStatus ? 1 : 0,
                openingStatus: this.openingStatus ? 1 : 0,
                datasetId: this.datasetId,
            }).then(res=>{
                this.loading = false
                if(res.data.code===0) {
                    this.current = 3
                    this.$emit("getList")
                    this.$store.dispatch("getUserPackageInfo")
                    this.id = res.data.obj.id
                    this.getLoginCode()
                } else {
                    toast(1, res.data.msg)
                }
            })
        },

        cancelTimer1(){
            clearInterval(this.timer1)
            this.timer1 = null
            this.show1 = false
            this.count1 = 1200
        },

        cancelTimer2(){
            clearInterval(this.timer2)
            this.timer2 = null
            this.show2 = false
            this.count2 = 5
        },
        cancelTimer3(){
            clearInterval(this.timer3)
            this.timer3 = null
        },

        // 若用户打开二维码弹窗 20 分钟后，将提示’扫码页面停留超时，10秒后将自动关闭窗口’点击‘取消关闭’，保留当前弹窗
        setInterval1(){
            this.timer1 = setInterval(() => {
                this.count1 -= 1
                console.log(this.count1)
                if(this.count1===10) this.show1 = true
                if(this.count1===0) this.beforeClose()
            }, 1000);
        },

        // 前端每隔 5 分钟会向服务器获取二维码
        setInterval2(){
            if(this.timer2) this.cancelTimer2()
            this.timer2 = setInterval(() => {
                this.count2 -= 1
                console.log(this.count2)
                // if(this.count2===10 && !this.show1) {
                //     this.show2 = true
                // }
                // if(this.count2===10 && this.show1){
                //     console.log("刷新提示和长时间提示同时出现, 不显示刷新提示")
                // }
                if(this.count2===0) {
                    // this.loading = true
                    // this.loginCode = ""
                    this.$post("/front/userWechat/getQrcode", {
                        id: this.id
                    }).then(res=>{
                        if(res.data.code===0) {
                            this.loginCode = "data:image/png;base64," + res.data.obj
                            // this.loading = false
                            this.setInterval2()
                        }else{
                            if(res.data.code===-1) {
                                setTimeout(() => {
                                    this.getLoginCode()
                                }, 2000);
                            }  
                        }
                    })
                }
            }, 1000);
        },

        //轮询获取登录状态
        setInterval3(){
            this.timer3 = setInterval(()=>{
                this.getStatus()
            },3000)
        },

        // 获取登录二维码
        getLoginCode(){
            this.loginCode = ""
            this.loading = true
            this.$post("/front/userWechat/getQrcode", {
                id: this.id
            }).then(res=>{
                if(res.data.code===0) {
                    this.loginCode = "data:image/png;base64," + res.data.obj
                    this.loading = false
                    this.setInterval1()
                    this.setInterval2()
                    this.setInterval3()
                }else{
                    if(res.data.code===-1) {
                        setTimeout(() => {
                            this.getLoginCode()
                        }, 2000);
                    }  
                }
            })
        },

        // 获取登录状态
        getStatus(){
            if(!this.dialogTableVisible){
                if(this.timer1) this.cancelTimer1()
                if(this.timer2) this.cancelTimer2() 
                if(this.timer3) this.cancelTimer3()
                return
            }
            this.$post("front/userWechat/wechatDetail", {
                id: this.id
            }).then(res=>{
                if(res.data.code===0) {
                    let status = res.data.obj.status
                    if(status===1) {
                        this.$store.dispatch("getWeChatList")
                        this.cancelTimer3()
                        this.$store.state.port = res.data.obj.wechatName
                        this.$store.state.scanId  = res.data.obj.id
                        this.$emit("callback")
                        this.$store.state.currentWeChat = {
                            currentWeChatId: res.data.obj.id,
                            currentUserWechatName: res.data.obj.wechatName,
                            currentOnLineStatus: res.data.obj.status
                        }
                        window.sessionStorage.setItem("currentWeChatId", res.data.obj.id)
                        window.sessionStorage.setItem("currentUserWechatName", res.data.obj.wechatName)
                        window.sessionStorage.setItem("currentOnLineStatus", res.data.obj.status)
                        this.beforeClose()
                    }
                }
            })
        },
    }
}
</script>


<style lang="less" scoped>
:deep(.el-dialog) {
    width: 880px !important;
    height: 80vh !important;
    border-radius: 10px;
    box-sizing: border-box
}
:deep(.el-dialog__body) {
    padding: 20px;
}
.stepVue {
    width: 100%;
    .dot {
        width: 25px;
        height: 25px;
        border-radius: 50%;
        background: #EEE;
        line-height: 25px;
        text-align: center;
        color: #999;
        margin-bottom: 10px;
    }
    .active {
        background: #0147fd;
        color: #fff;
    }
    .line {
        width: 100px;
        height: 1px;
        background: #EEE;
        margin-top: 12px;
    }
    span {
        color: #999;
        font-size: 12px;
    }
    .textActive {
        color: #0147fd;
        font-weight: 600; 
    }
}
.stepContent {
    width: 100%;
    height: calc(80vh - 64px - 48px - 40px - 40px);
    position: relative;
    .inpVue {
        width: 100%;
        margin-top: 20px;
        .label {
            color: #333;
            font-size: 12px;
        }
        textarea {
            width: 100%;
            height: 60px;
            border: #DCDFE6 1px solid;
            display: block;
            box-sizing: border-box;
            resize: none;
            border-radius: 4px;
            margin-top: 10px;
            font-family: PingFangSC, PingFang SC;
            padding: 10px;
            font-size: 13px;
            line-height: 1.4;
        }
        ::-webkit-input-placeholder { /* WebKit browsers */
            color: #AAA;
            font-size: 13px;
            font-family: PingFangSC, PingFang SC;
        }
        :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
            color: #AAA;
            font-size: 13px;
            font-family: PingFangSC, PingFang SC;
        }
        ::-moz-placeholder { /* Mozilla Firefox 19+ */
            color: #AAA;
            font-size: 13px;
            font-family: PingFangSC, PingFang SC;
        }
        :-ms-input-placeholder { /* Internet Explorer 10+ */
            color: #AAA;
            font-size: 13px;
            font-family: PingFangSC, PingFang SC;
        }
        textarea::-webkit-scrollbar {
            width: 0;
            height: 0;
        }
    }
    .btnVue {
        width: 100%;
        height: 40px;
        position: absolute;
        left: 0;
        bottom: 0;
        background: #fff;
        z-index: 999;
        .cancel,.btn {
            width: 250px;
            height: 40px;
            text-align: center;
            line-height: 40px;
            border-radius: 5px;
            cursor: pointer;
        }
        .cancel {
            background: #f5f5f5;
        }
        .btn {
            background: #0147fd;
            color: #fff;
            span {
                color: #fff;
            }
        }
    }
    .selectVue {
        width: 100%;
        height: calc(80vh - 64px - 48px - 40px - 40px - 40px);
        margin-top: 10px;
        overflow-y: scroll;
        .select {
            width: 405px;
            height: 120px;
            border-radius: 6px;
            border: 1px solid #EEE;
            margin-bottom: 10px;
            cursor: pointer;
            padding: 10px;
        }
        .active {
            border: #0147fd 1px solid;
            background: rgba(1,71,253, 0.1);
        }
        .li {
            font-size: 12px;
            color: #444;
            padding-top: 6px;
            line-height: 1.2;
        }
    }
    .selectVue::-webkit-scrollbar {
        width: 0;
        height: 0;
    }
    .h8 {
        padding-top: 50px;
        color: #606266;
    }
    .code {
        width: 300px;
        height: 300px;
        background: #f5f5f5;
        border-radius: 4px;
        span {
            font-size: 28px;
        }
    }
    .btn {
        width: 200px;
        height: 38px;
        border-radius: 6px;
        line-height: 38px;
        text-align: center;
        color: #fff;
        text-align: center;
        background: #0147fd;
        cursor: pointer;
    }
}

</style>